﻿using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.X509;
using WallpaperDemo.Models;

namespace WallpaperDemo
{
    public class UserService
    {
        private readonly WallpapersContext db;
        public UserService(WallpapersContext context) 
        {
            db = context;
        }

        public List<User> Users
        {
            get
            {
                return db.Users
                       .Include(o => o.UserLikes)
                       .ToList<User>();
            }
        }

        public void AddUser(User user)
        {
            user.UserId = Guid.NewGuid().ToString();
            db.Users.Add(user);
            db.SaveChanges();
        }

        public void AddLike(Like like)
        {
            like.LikeId = Guid.NewGuid().ToString();
            db.Likes.Add(like);
            
            var user = db.Users.Include(u => u.UserLikes).FirstOrDefault(u => u.UserId == like.UserId);
            if(!user.UserLikes.Exists(u => u.WallpaperId == like.WallpaperId))
            {
                user.UserLikes.Add(like);
            }
            
            db.SaveChanges();
        }

        public void RemoveUser(string id)
        {
            var q = db.Users
                .Include(o => o.UserLikes)
                .SingleOrDefault(o => o.UserId == id);
            if (q == null) return;
            db.Likes.RemoveRange(q.UserLikes);
            db.Users.Remove(q);
            db.SaveChanges();
        }

        public User QueryUser_Id(string id)
        {
            var query = db.Users
                        .Include(o => o.UserLikes).Include(o => o.UserTags)
                        .SingleOrDefault(o => o.UserId == id);
            return query;
        }
        
        public List<Like> QueryUser_Tag(string id, string tag)
        {
            var query = db.Likes
                        .Include(l => l.LikeWallpaper)
                        .Where(l => l.UserId == id && l.LikeTag == tag);
            return query.ToList();
        }

        public User QueryUser_Name(string name)
        {
            var query = db.Users
                        .Include(l => l.UserLikes).Include(l => l.UserTags)
                        .SingleOrDefault(l => l.UserName == name);
            if (query.IsLogin == false) return null;
            return query;
        }

        public User QueryUser_LogIn(string name, string password)
        {
            var query = db.Users
                        .Include(l => l.UserLikes).Include(l => l.UserTags)
                        .SingleOrDefault(l => l.UserName == name && l.UserPassword == password);
            query.IsLogin = true;
            return query;
        }
    }
}
